/*
 * Copyright (c) 2011, Michael Hengler (developer (at) hengler (dot) de),
 * Nikolaus Moll (developer (at) miblounge (dot) net).
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of the Jombi project nor the
 * names of its contributors may be used to endorse or promote products
 * derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL JOMBI BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */
package net.miblounge.jombi.impl.widgets;

import java.util.HashMap;
import java.util.Map;

import net.miblounge.jombi.impl.util.PositionConvert;
import net.miblounge.jombi.impl.util.TabPositionConvert;

import org.jowidgets.common.types.Dimension;
import org.jowidgets.common.types.Position;
import org.jowidgets.common.widgets.factory.IGenericWidgetFactory;
import org.jowidgets.spi.widgets.ITabFolderSpi;
import org.jowidgets.spi.widgets.ITabItemSpi;
import org.jowidgets.spi.widgets.setup.ITabFolderSetupSpi;
import org.jowidgets.spi.widgets.setup.ITabItemSetupSpi;
import org.jowidgets.util.Assert;
import org.jowidgets.util.TypeCast;

import com.trolltech.qt.core.QRect;
import com.trolltech.qt.gui.QContextMenuEvent;
import com.trolltech.qt.gui.QTabBar;
import com.trolltech.qt.gui.QTabWidget;
import com.trolltech.qt.gui.QWidget;

public class TabFolderImpl extends QtControl implements ITabFolderSpi {

	private final IGenericWidgetFactory widgetFactory;
	private final boolean tabsClosable;
	private final Map<QWidget, TabItemImpl> items;

	public TabFolderImpl(final IGenericWidgetFactory widgetFactory, final ITabFolderSetupSpi setup) {
		super(new JoTabWidget());
		getUiReference().setParent(this);

		getUiReference().setTabPosition(TabPositionConvert.convert(setup.getTabPlacement()));

		this.items = new HashMap<QWidget, TabItemImpl>();

		this.tabsClosable = setup.isTabsCloseable();
		if (tabsClosable) {
			this.getUiReference().setTabsClosable(tabsClosable);
		}
		this.widgetFactory = widgetFactory;

		getUiReference().currentChanged.connect(this, "currentChanged(int)");
		getUiReference().tabCloseRequested.connect(this, "tabCloseRequested(int)");
	}

	// Qt event handler
	protected void currentChanged(final int index) {
		final QWidget widgetItem = getUiReference().widget(index);

		if (!items.containsKey(widgetItem)) {
			return;
		}

		final TabItemImpl item = items.get(widgetItem);
		item.fireSelected();
	}

	// Qt event handler
	protected void tabCloseRequested(final int index) {
		final QWidget widgetItem = getUiReference().widget(index);

		if (!items.containsKey(widgetItem)) {
			return;
		}

		final TabItemImpl item = items.get(widgetItem);
		if (tabsClosable) {
			final boolean veto = item.fireOnClose();
			if (veto) {
				return;
			}

			getUiReference().removeTab(index);
		}
	}

	// Qt event handler
	protected void tabContextMenuRequested(final int index, final Position pos) {
		final QWidget widgetItem = getUiReference().widget(index);

		if (!items.containsKey(widgetItem)) {
			return;
		}

		final TabItemImpl item = items.get(widgetItem);
		item.fireContextMenu(pos);
	}

	@Override
	public JoTabWidget getUiReference() {
		return (JoTabWidget) super.getUiReference();
	}

	@Override
	public void removeItem(final int index) {
		getUiReference().removeTab(index);
		items.remove(index);
	}

	@Override
	public ITabItemSpi addItem(final ITabItemSetupSpi setup) {
		final TabItemImpl result = new TabItemImpl(widgetFactory, getUiReference());
		items.put(result.getTabItem(), result);
		return result;
	}

	@Override
	public ITabItemSpi addItem(final int index, final ITabItemSetupSpi setup) {
		final TabItemImpl result = new TabItemImpl(widgetFactory, getUiReference(), Integer.valueOf(index));
		items.put(result.getTabItem(), result);
		return result;
	}

	@Override
	public void setSelectedItem(final int index) {
		getUiReference().setCurrentIndex(index);
	}

	@Override
	public int getSelectedIndex() {
		return getUiReference().currentIndex();
	}

	@Override
	public void detachItem(final ITabItemSpi item) {
		Assert.paramNotNull(item, "item");
		final TabItemImpl itemImpl = TypeCast.toType(item, TabItemImpl.class);
		if (!items.containsKey(itemImpl.getUiReference())) {
			throw new IllegalArgumentException("Item is not attached to this folder");
		}
		if (itemImpl.isDetached()) {
			throw new IllegalArgumentException("Item is already detached");
		}
		items.remove(item);
		itemImpl.detach();
	}

	@Override
	public void attachItem(final ITabItemSpi item) {
		Assert.paramNotNull(item, "item");
		final TabItemImpl itemImpl = TypeCast.toType(item, TabItemImpl.class);
		if (!itemImpl.isDetached()) {
			throw new IllegalArgumentException("Item is not detached");
		}
		itemImpl.attach(getUiReference(), null);
		items.put(itemImpl.getTabItem(), itemImpl);
	}

	@Override
	public void attachItem(final int index, final ITabItemSpi item) {
		Assert.paramNotNull(item, "item");
		final TabItemImpl itemImpl = TypeCast.toType(item, TabItemImpl.class);
		if (!itemImpl.isDetached()) {
			throw new IllegalArgumentException("Item is not detached");
		}
		itemImpl.attach(getUiReference(), Integer.valueOf(index));
		items.put(itemImpl.getTabItem(), itemImpl);
	}

	@Override
	public Dimension computeDecoratedSize(final Dimension clientAreaSize) {
		// TODO NM implement
		return clientAreaSize;
	}

}

class JoTabWidget extends QTabWidget {

	public JoTabWidget() {}

	public void setParent(final TabFolderImpl tabFolderImpl) {
		setTabBar(new JoTabBar(tabFolderImpl));
	}

	//		public JoTabBar getTabBar() {
	//			return (JoTabBar) super.tabBar();
	//		}

}

class JoTabBar extends QTabBar {
	private final TabFolderImpl tabFolderImpl;

	public JoTabBar(final TabFolderImpl tabFolderImpl) {
		this.tabFolderImpl = tabFolderImpl;
	}

	@Override
	protected void contextMenuEvent(final QContextMenuEvent event) {
		for (int i = 0; i < this.count(); i++) {
			final QRect rect = tabRect(i);
			if (rect.contains(event.pos())) {
				event.accept();

				tabFolderImpl.tabContextMenuRequested(i, PositionConvert.convert(event.globalPos()));
			}
		}
	}

}
